# coding=utf-8
from django.shortcuts import render
from django.http import HttpResponse, StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseNotFound
from web.querymodels import *
from web.crawl import *
# from multiprocessing import Pool
import threadpool
import thread
import json
# Create your views here.

# import the logging library
import logging
logger = logging.getLogger('django')


def admin(request):
    return render(request, 'books/admin.html', {})


@csrf_exempt
def check_log(request):
    while True:
        data = take_log()
        if data:
            response = json.dumps(data)
            return HttpResponse(response)


@csrf_exempt
def crawl(request):
    if request.method == 'POST':
        start_book_id = request.POST.get('start_book_id', None)
        end_book_id = request.POST.get('end_book_id', None)
        v = request.POST.get('v', None)

        try:
            start_book_id = int(start_book_id)
            end_book_id = int(end_book_id)
            v = int(v)

        except Exception as e:
            response = json.dumps([False, str(e)])
            return HttpResponse(response)

        else:

            # pool = Pool(processes=2)
            data = [[book_id, v] for book_id in range(start_book_id, end_book_id)]
            pool = threadpool.ThreadPool(4)
            requests = threadpool.makeRequests(update_book, data)
            [pool.putRequest(req) for req in requests]
            # for book_id in range(start_book_id, end_book_id+1):
                # thread.start_new_thread(main, (book_id,))
                # pool.apply_async(main, (book_id,))
                # pool.putRequest()
            response = json.dumps([True, u'正在后台爬取%d - %d编号的小说'%(start_book_id, end_book_id)])

            return HttpResponse(json.dumps(response))
    else:

        return render(request, 'books/crawl.html', {})


@csrf_exempt
def checks(request):
    if request.method == 'POST':
        start_book_id = request.POST.get('start_book_id', None)
        end_book_id = request.POST.get('end_book_id', None)

        try:
            start_book_id = int(start_book_id)
            end_book_id = int(end_book_id)

        except Exception as e:
            response = json.dumps([False, str(e)])
            return HttpResponse(response)

        else:
            per = []
            # for book_id in range(start_book_id, end_book_id+1):
            #     per.append(check(book_id))
            per = check(start_book_id, end_book_id)
            response = json.dumps([True, per])
        return HttpResponse(response)

    else:
        response = json.dumps([False, u'该请求不是POST请求'])
        return HttpResponse(response)


def home(request):
    books = Book.objects()
    return render(request, 'books/home.html', {'books': books})


def debug(request):
    with open('debug.log', 'r') as f:
        info = f.read()
    return HttpResponse(info)


def baidu_verify_d9c0islUCd(request):
    return render(request, 'baidu_verify_d9c0islUCd.html', {})


def book(request, book_id):
    try:
        the_book, pages = get_info(book_id)
    except Exception as e:
        return HttpResponse(str(e))

    context = {
        'the_book': the_book,
        'pages': pages,
    }
    return render(request, 'books/book.html', context)


def page(request, book_id, page_id):
    page_id = int(page_id)
    current_page = get_page(book_id, page_id)
    if (page_id - 1) < -1:
        pre_page = None
    else:
        pre_page = page_id - 1
    next_page = page_id + 1
    context = {
        'current_page': current_page,
        'pre_page': pre_page,
        'next_page': next_page,
        'book_id': book_id,
    }


    return render(request, 'books/page.html', context)
